package com.example.ercmssystem2.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.ercmssystem2.service.EventService;
import com.example.ercmssystem2.service.ResourceService;
import com.example.ercmssystem2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.ercmssystem2.entity.Event;
import java.time.LocalDateTime;
import com.example.ercmssystem2.entity.User;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class ApiController {

    @Autowired
    private EventService eventService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;

    @GetMapping("/test-auth")
    public ResponseEntity<?> testAuth() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        if (authentication == null || !authentication.isAuthenticated() || 
            "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body(Map.of(
                "success", false,
                "message", "未认证"
            ));
        }
        
        User currentUser = userService.getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).body(Map.of(
                "success", false,
                "message", "用户信息获取失败"
            ));
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "认证成功");
        response.put("user", Map.of(
            "id", currentUser.getId(),
            "username", currentUser.getUsername(),
            "realName", currentUser.getRealName(),
            "role", currentUser.getRole()
        ));
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/health")
    public ResponseEntity<?> health() {
        return ResponseEntity.ok(Map.of(
            "status", "UP",
            "message", "系统运行正常"
        ));
    }

    @GetMapping("/info")
    public ResponseEntity<?> info() {
        return ResponseEntity.ok(Map.of(
            "application", "ERCMS System",
            "version", "2.0",
            "description", "应急指挥管理系统"
        ));
    }

    /**
     * 仪表盘统计API
     * GET /api/dashboard/stats
     * 返回: {success:true, data:{pendingEvents, inProgressEvents, availableResources, activeUsers}}
     */
    @GetMapping("/dashboard/stats")
    public Map<String, Object> dashboardStats() {
        Map<String, Object> data = new HashMap<>();
        data.put("pendingEvents", eventService.findByStatus("PENDING").size());
        data.put("inProgressEvents", eventService.findByStatus("IN_PROGRESS").size());
        data.put("availableResources", resourceService.findAvailableResources().size());
        data.put("activeUsers", userService.getAvailableUsers().size());
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", true);
        resp.put("data", data);
        return resp;
    }

    @GetMapping("/events/recent")
    public Map<String, Object> getRecentEvents() {
        Map<String, Object> resp = new HashMap<>();
        try {
            // 获取最近30天的事件，按开始时间倒序排列，取前10个
            LocalDateTime startTime = LocalDateTime.now().minusDays(30);
            List<Event> recentEvents = eventService.findAllEvents().stream()
                .filter(event -> event.getStartTime() != null && event.getStartTime().isAfter(startTime))
                .sorted((e1, e2) -> e2.getStartTime().compareTo(e1.getStartTime()))
                .limit(10)
                .toList();
            
            resp.put("success", true);
            resp.put("data", recentEvents);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("message", "获取最近事件失败: " + e.getMessage());
        }
        return resp;
    }
} 